//
//  XLConversationInputToolbar.m
//  XLConversationInputView
//
//  Created by ilongge on 2022/8/3.
//

#import "XLConversationInputToolbar.h"
#import "XLCIViewResourcesManager.h"
#import "XLEmojiInputView.h"
#import "XLConversationInputViewDef.h"
#import "XLEmojiManager.h"
#import "XLCvstInputMoreItemModel.h"
#import "XLCvstInputMoreItemModel+Inside.h"

#define EmojiKeyBoardHeight  300
#define MinTextBackgorundViewHeight 39
#define MaxTextBackgorundViewHeight 80
#define MinSendButtonWidth 24
#define MaxSendButtonWidth 50

@interface XLConversationInputToolbar()
<
UITextViewDelegate
>

@property (nonatomic, assign) CGRect orginRect;
@property (nonatomic, assign) CGRect keyBoardRect;
@property (nonatomic, strong) XLEmojiInputView *emojiInput;
@property (nonatomic, assign) NSRange selectRange;
@property (nonatomic, strong) XLCvstInputMoreItemModel *textItem;
@property (nonatomic, strong) XLCvstInputMoreItemModel *atItem;
@property (nonatomic, strong) XLCvstInputMoreItemModel *atdelItem;
@end

@implementation XLConversationInputToolbar
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _orginRect = frame;
        [self initSubviews];
    }
    return self;
}

- (void)initSubviews {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textViewTextDidChange)
                                                 name:UITextViewTextDidChangeNotification
                                               object:self.messageTextView];
    
    _messageTextBackgorundViewHeight = MinTextBackgorundViewHeight;
    _sendButtonWidth = MinSendButtonWidth;
    self.sendMessageButton.hidden = YES;
    self.recordAudioButton.hidden = YES;
    self.layer.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:1].CGColor;
    [self addSubview:self.voiceIconButton];
    [self addSubview:self.messageTextBackgorundView];
    [self.messageTextBackgorundView addSubview:self.messageTextView];
    [self.messageTextBackgorundView addSubview:self.recordAudioButton];
    [self addSubview:self.emojiIconButton];
    [self addSubview:self.sendMessageButton];
    [self addSubview:self.addMoreItemButton];
}
- (void)keyboardWillShow:(NSNotification *)notification {
    self.addMoreItemButton.selected = NO;
}
- (void)keyboardWillHide:(NSNotification *)notification {
    self.emojiIconButton.selected = NO;
    [self.messageTextView resignFirstResponder];
    self.messageTextView.inputView = nil;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect rect = self.orginRect;
    rect.size.height = _messageTextBackgorundViewHeight + 10;
    self.frame = rect;
    CGFloat buttonHeight = MinTextBackgorundViewHeight + 10;
    CGFloat buttonWidth = 24;
    CGFloat itemMargin = 10;
    CGFloat textTopMargin = 1.5;
    self.voiceIconButton.frame = CGRectMake(itemMargin,
                                            rect.size.height-buttonHeight,
                                            buttonWidth,
                                            buttonHeight);
    self.addMoreItemButton.frame = CGRectMake(rect.size.width - buttonWidth - itemMargin,
                                              rect.size.height - buttonHeight,
                                              buttonWidth,
                                              buttonHeight);
    self.sendMessageButton.frame = CGRectMake(rect.size.width - self.sendButtonWidth - itemMargin,
                                              rect.size.height - 37,
                                              self.sendButtonWidth,
                                              25);
    self.emojiIconButton.frame = CGRectMake(CGRectGetMinX(self.sendMessageButton.frame) - buttonWidth - itemMargin,
                                            rect.size.height - buttonHeight,
                                            buttonWidth,
                                            buttonHeight);
    self.messageTextBackgorundView.frame = CGRectMake(CGRectGetMaxX(self.voiceIconButton.frame)+itemMargin,
                                                      rect.size.height - _messageTextBackgorundViewHeight - 5,
                                                      CGRectGetMinX(self.emojiIconButton.frame) - itemMargin - CGRectGetMaxX(self.voiceIconButton.frame) - itemMargin,
                                                      _messageTextBackgorundViewHeight);
    self.messageTextView.frame = CGRectMake(5,
                                            textTopMargin,
                                            self.messageTextBackgorundView.frame.size.width - 10,
                                            self.messageTextBackgorundView.frame.size.height - textTopMargin * 2);
    self.recordAudioButton.frame = self.messageTextView.frame;
    if(self.layoutSubviewsBlock){
        self.layoutSubviewsBlock();
    }
}

#pragma mark  按钮动作
/// 切换到语音
- (void)voiceIconButtonAction:(UIButton *)sender {
    if (self.emojiIconButton.isSelected) {
        self.emojiIconButton.selected = NO;
    }
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        self.messsageTextTempString = self.messageTextView.text;
        self.messageTextView.text = nil;
        self.recordAudioButton.hidden = NO;
        self.messageTextView.inputView = nil;
        [self.messageTextView resignFirstResponder];
        [self.messageTextView reloadInputViews];
    }
    else{
        self.messageTextView.text = self.messsageTextTempString;
        self.recordAudioButton.hidden = YES;
        self.messageTextView.inputView = nil;
        [self.messageTextView becomeFirstResponder];
        [self.messageTextView reloadInputViews];
    }
    if (self.voiceIconButtonBlock) {
        self.voiceIconButtonBlock(sender.isSelected);
    }
    [self textViewTextDidChange];
}


- (void)emojiIconButtonAction:(UIButton *)sender {
    if (self.voiceIconButton.isSelected) {
        self.voiceIconButton.selected = NO;
        self.messageTextView.text = self.messsageTextTempString;
        self.recordAudioButton.hidden = YES;
        [self textViewTextDidChange];
    }
    if (self.voiceIconButtonBlock) {
        self.voiceIconButtonBlock(self.voiceIconButton.isSelected);
    }
    if (self.addMoreItemButton.isSelected) {
        self.addMoreItemButton.selected = NO;
    }
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        if (self.keyBoardRect.size.height == 0) {
            CGFloat width = [UIScreen mainScreen].bounds.size.width;
            self.keyBoardRect = CGRectMake(0, 0, width, 300);
        }
        self.messageTextView.inputView = self.emojiInput;
        NSRange range = self.messageTextView.selectedRange;
        self.messageTextView.selectedRange = range;
        self.messageTextView.inputAccessoryView = nil;
    }
    else{
        self.messageTextView.inputView = nil;
        self.messageTextView.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    [self.messageTextView becomeFirstResponder];
    [self.messageTextView reloadInputViews];
    if (self.addMoreItemActionBlock) {
        self.addMoreItemActionBlock(self.addMoreItemButton.isSelected);
    }
}

- (void)addMoreItemButtonAction:(UIButton *)sender {
    if (self.voiceIconButton.isSelected) {
        self.voiceIconButton.selected = NO;
        self.recordAudioButton.hidden = YES;
        [self textViewTextDidChange];
    }
    if (self.voiceIconButtonBlock) {
        self.voiceIconButtonBlock(self.voiceIconButton.isSelected);
    }
    self.messageTextView.inputView = nil;
    [self.messageTextView resignFirstResponder];
    [self.messageTextView reloadInputViews];
    self.messageTextView.text = nil;
    sender.selected = !sender.isSelected;
    if (self.addMoreItemActionBlock) {
        self.addMoreItemActionBlock(sender.isSelected);
    }
}

- (void)sendMessageButtonction {
    if (self.sendMessageBlock) {
        if (self.textItem == nil) {
            self.textItem = [[XLCvstInputMoreItemModel alloc] initWithType:MoreItemType_Text
                                                                 titleText:@"Text"];
        }
        self.sendMessageBlock(self.textItem, self.messageTextView.text);
        [self.messageTextView unmarkText];
        self.messageTextView.text = nil;
        self.messsageTextTempString = nil;
        [self textViewTextDidChange];
    }
}

#pragma mark  文本计算

- (void)textViewTextDidChange
{
    UITextView *textView = self.messageTextView;
    if (textView.text.length > self.maxMessageTextLength) {
        textView.text = [textView.text substringToIndex:self.maxMessageTextLength];
    }
    if (textView.text.length > 0 && self.sendButtonWidth == MinSendButtonWidth) {
        [UIView animateWithDuration:0.33
                         animations:^{
            self.addMoreItemButton.hidden = YES;
            self.sendMessageButton.hidden = NO;
            self.sendButtonWidth = MaxSendButtonWidth;
            [self layoutIfNeeded];
        }];
    }
    else if (textView.text.length == 0 && self.sendButtonWidth == MaxSendButtonWidth) {
        [UIView animateWithDuration:0.33
                         animations:^{
            self.addMoreItemButton.hidden = NO;
            self.sendMessageButton.hidden = YES;
            self.sendButtonWidth = MinSendButtonWidth;
            [self layoutIfNeeded];
        }];
    } 
    float  messageTextBackgorundViewHeight = [self heightForTextBackgroundView:textView];
    [self setMessageTextBackgorundViewHeight:messageTextBackgorundViewHeight];
}

-(void)setMessageTextBackgorundViewHeight:(CGFloat)messageTextBackgorundViewHeight {
    _messageTextBackgorundViewHeight = messageTextBackgorundViewHeight;
    if (self.messageTextHeightChangedBlock) {
        self.messageTextHeightChangedBlock(_messageTextBackgorundViewHeight + 10);
    }
    [self layoutSubviews];
}

#pragma mark - UITextView height
- (float)heightForTextBackgroundView:(UITextView *)textView {
    
    CGSize size = [textView.attributedText boundingRectWithSize:CGSizeMake(self.messageTextView.frame.size.width, MAXFLOAT)
                                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                        context:nil].size;
    CGFloat height = size.height;
    
    if (height < MinTextBackgorundViewHeight) {
        height = MinTextBackgorundViewHeight;
    }
    else if (height > MaxTextBackgorundViewHeight) {
        height = MaxTextBackgorundViewHeight;
    }
    else {
        height = size.height;
    }
    return height;
}

- (XLEmojiInputView *)emojiInput
{
    if (_emojiInput == nil) {
        WeakSelf(weakSelf);
        _emojiInput = [[XLEmojiInputView alloc] initWithFrame:CGRectMake(0,
                                                                         0,
                                                                         self.keyBoardRect.size.width,
                                                                         self.keyBoardRect.size.height - 44)];
        
        _emojiInput.inputEmojiBlock = ^(NSString *emojiTitle,
                                        NSString *emojiName,
                                        UIImage *emojiImage) {
            StrongSelf(strongSelf);
            [strongSelf inputEmojiStringToTextField:emojiTitle
                                       andEmojiName:emojiName
                                      andEmojiImage:emojiImage];
        };
        
        _emojiInput.deleteEmojiBlock = ^{
            StrongSelf(strongSelf);
            [strongSelf deleteEmojiAction];
        };
    }
    _emojiInput.frame = CGRectMake(0,
                                   0,
                                   self.keyBoardRect.size.width,
                                   self.keyBoardRect.size.height - 44);
    return _emojiInput;
}

- (void)inputEmojiStringToTextField:(NSString *)emojiTitle
                       andEmojiName:(NSString *)emojiName
                      andEmojiImage:(UIImage *)emojiImage
{
    NSRange range = self.messageTextView.selectedRange;
    NSString *textLeft = [self.messageTextView.text substringToIndex:range.location];
    NSString *textRight = [self.messageTextView.text substringFromIndex:range.location];
    if (emojiTitle.length) {
        NSRange range = self.messageTextView.selectedRange;
        self.messageTextView.text = [NSString stringWithFormat:@"%@%@%@",textLeft,emojiTitle,textRight];
        self.messageTextView.selectedRange = NSMakeRange(range.location+emojiTitle.length, 0);
        [self textViewTextDidChange];
    }
}

- (void)deleteEmojiAction
{
    NSRange range = self.messageTextView.selectedRange;
    if (range.location == 0) {
        return;
    }
    [self textView:self.messageTextView shouldChangeTextInRange:NSMakeRange(range.location-1, 1) replacementText:@""];
    [self textViewTextDidChange];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@""]) {
        NSString *rightSubString = [textView.text substringWithRange:range];
        if ([rightSubString isEqualToString:@"]"]) {
            NSInteger start = range.location - 1;
            for (NSInteger index = start; (index >= start - 3) && index >= 0; index--) {
                NSString *leftSubString = [textView.text substringWithRange:NSMakeRange(index, 1)];
                if ([leftSubString isEqualToString:@"["]) {
                    NSRange subRange = NSMakeRange(index, range.location-index+1);
                    NSString *subString = [textView.text substringWithRange:subRange];
                    BOOL isEmoji = [XLEmojiManager isEmojiImageNameForEmojiString:subString];
                    if (isEmoji) {
                        textView.text = [textView.text stringByReplacingCharactersInRange:subRange
                                                                               withString:@""];
                        textView.selectedRange = NSMakeRange((range.location-subRange.length>=0?range.location-subRange.length:0)+1, 0);
                        [self textViewTextDidChange];
                        return NO;
                    }
                }
            }
        }
        else if ([rightSubString isEqualToString:@" "]) {
            NSInteger start = range.location - 1;
            for (NSInteger index = start; index >= 0; index--) {
                NSString *leftSubString = [textView.text substringWithRange:NSMakeRange(index, 1)];
                if ([leftSubString isEqualToString:@"@"]) {
                    NSRange subRange = NSMakeRange(index, range.location-index+1);
                    NSString *subString = [textView.text substringWithRange:subRange];
                    if (self.atSomeoneBlock) {
                        if (self.atdelItem == nil) {
                            self.atdelItem = [[XLCvstInputMoreItemModel alloc] initWithType:MoreItemType_AtSomeoneDelete
                                                                                  titleText:@"AtSomeoneDelete"];
                        }
                        BOOL ret = self.atSomeoneBlock(self.atdelItem, subString);
                        if (ret) {
                            subRange = NSMakeRange(textView.text.length-subString.length, subString.length);
                            textView.text = [textView.text stringByReplacingCharactersInRange:subRange
                                                                                   withString:@""];
                        }
                        else{
                            subRange = NSMakeRange(textView.text.length - 1, 1);
                            textView.text = [textView.text stringByReplacingCharactersInRange:subRange
                                                                                   withString:@""];
                        }
                    }
                    [self textViewTextDidChange];
                    return NO;
                }
            }
        }
        else{
            UITextInputMode *inputMode = [textView textInputMode];
            if ([inputMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
                return YES;
            }
            else{
                textView.text = [textView.text stringByReplacingCharactersInRange:range
                                                                       withString:@""];
                textView.selectedRange = NSMakeRange((range.location-range.length>=0?range.location-range.length:0)+1, 0);
                [self textViewTextDidChange];
                return NO;
            }
        }
    }
    else if ([text hasSuffix:@"@"]) {
        // 长度超长
        textView.text = [NSString stringWithFormat:@"%@%@",textView.text,text];
        if (textView.text.length > self.maxMessageTextLength) {
            textView.text = [textView.text substringToIndex:self.maxMessageTextLength];
        }
        else{
            if (self.atSomeoneBlock) {
                if (self.atItem == nil) {
                    self.atItem = [[XLCvstInputMoreItemModel alloc] initWithType:MoreItemType_AtSomeone
                                                                       titleText:@"AtSomeone"];
                }
                self.atSomeoneBlock(self.atItem, nil);
            }
        }
        [self textViewTextDidChange];
        return NO;
    }
    return YES;
}

#pragma mark 懒加载

- (UIButton *)voiceIconButton {
    if (_voiceIconButton == nil) {
        _voiceIconButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_voiceIconButton setImage:[XLCIViewResourcesManager imageNamed:@"ToolBar_语音_icon"] forState:UIControlStateNormal];
        [_voiceIconButton setImage:[XLCIViewResourcesManager imageNamed:@"ToolBar_键盘_icon"] forState:UIControlStateSelected];
        [_voiceIconButton addTarget:self action:@selector(voiceIconButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceIconButton;
}

- (UIView *)messageTextBackgorundView {
    if (_messageTextBackgorundView == nil) {
        _messageTextBackgorundView = [[UIView alloc] initWithFrame:CGRectZero];
        _messageTextBackgorundView.layer.cornerRadius = 6;
        _messageTextBackgorundView.backgroundColor = [UIColor whiteColor];
    }
    return _messageTextBackgorundView;
}

- (UITextView *)messageTextView {
    if (_messageTextView == nil) {
        _messageTextView = [[UITextView alloc] init];
        _messageTextView.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
        _messageTextView.layer.cornerRadius = 6;
        _messageTextView.font = [UIFont fontWithName:kXLCIPingFangSC_Regular size:12];
        _messageTextView.inputAccessoryView = [[UIView alloc] initWithFrame:CGRectZero];
        _messageTextView.delegate = self;
        _messageTextView.autocorrectionType = NO;
    }
    return _messageTextView;
}

- (UIButton *)recordAudioButton {
    if (_recordAudioButton == nil) {
        _recordAudioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _recordAudioButton.titleLabel.font = [UIFont fontWithName:kXLCIPingFangSC_Regular size:14];
        [_recordAudioButton setTitleColor:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1] forState:UIControlStateNormal];
        [_recordAudioButton setTitle:@"按住说话" forState:UIControlStateNormal];
    }
    return _recordAudioButton;
}

- (UIButton *)emojiIconButton {
    if (_emojiIconButton == nil) {
        _emojiIconButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_emojiIconButton setImage:[XLCIViewResourcesManager imageNamed:@"ToolBar_表情_icon"] forState:UIControlStateNormal];
        [_emojiIconButton setImage:[XLCIViewResourcesManager imageNamed:@"ToolBar_键盘_icon"] forState:UIControlStateSelected];
        [_emojiIconButton addTarget:self action:@selector(emojiIconButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _emojiIconButton;
}

- (UIButton *)addMoreItemButton {
    if (_addMoreItemButton == nil) {
        _addMoreItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addMoreItemButton setImage:[XLCIViewResourcesManager imageNamed:@"ToolBar_添加_icon"] forState:UIControlStateNormal];
        [_addMoreItemButton addTarget:self action:@selector(addMoreItemButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addMoreItemButton;
}

- (UIButton *)sendMessageButton {
    if (_sendMessageButton == nil) {
        _sendMessageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendMessageButton setTitle:@"发送" forState:UIControlStateNormal];
        _sendMessageButton.layer.cornerRadius = 4;
        _sendMessageButton.titleLabel.font = [UIFont fontWithName:kXLCIPingFangSC_Regular size:14];
        _sendMessageButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:145/255.0 blue:234/255.0 alpha:1.0];
        [_sendMessageButton addTarget:self action:@selector(sendMessageButtonction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendMessageButton;
}
@end
